﻿using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;

namespace Core.Scene
{
    public class LoadSceneNode : AbstractSceneNode
    {
        private AsyncOperation asyncOperation;
        private float progress = 0;

        public override void Start()
        {
            //log.d("LoadSceneNode.Start");
            IsComplete = false;
            progress = 0;

            S.mono.StartCoroutine(LoadScene());
        }

        public override void Update()
        {
            if (asyncOperation == null || IsComplete)
            {
                return;
            }

            progress = asyncOperation.progress;

            if (progress >= 0.9f)
            {
                progress = 1.0f;
            }

            if (asyncOperation.isDone && Mathf.Approximately(progress, 1.0f))
            {
                IsComplete = true;
            }
        }

        public override void Finish()
        {
            S.Evt.Run(SceneEvent.START_SWITCH);
            //log.d("LoadSceneNode.Finish");
        }

        IEnumerator LoadScene()
        {
            var conf = Scene.Conf;
            if (string.IsNullOrWhiteSpace(conf.LightingPath) == false)
            {
                if (Global.ResMode == EResMode.AssetDatabase)
                {
                    asyncOperation = G.Res.LoadSceneAsync(conf.LightingPath, conf.LoadSceneMode);
                }
                else
                {
                    asyncOperation = SceneManager.LoadSceneAsync(conf.SceneName, conf.LoadSceneMode);
                }
            }
            yield return asyncOperation;

            if (conf.LoadSceneMode == LoadSceneMode.Additive)
            {
                SceneManager.SetActiveScene(SceneManager.GetSceneByName(conf.SceneName));
            }
        }
    }
}
